package com.njym.java.oss.constants;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @program: UploadService
 * @description:
 * @author: wb
 * @create: 2019-11-22 16:06
 **/
@Service
@Slf4j
public class UploadService {

    private static final List<String> ALLOW_TYPES = Arrays.asList("image/png", "image/jpeg", "image/bmg");

    public String uploadImage(MultipartFile file) {
        try {
            //校验文件类型
            String contentType = file.getContentType();
            if (!ALLOW_TYPES.contains(contentType)) {

            }
            //校验文件的内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {

            }
            //设置文件名称
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date();
            System.out.println(dateFormat.format(date));

            //准备目标路径
            String toFilePath = "D:\\nginx-1.15.2\\html\\family-app\\static\\chatimg\\" + dateFormat.format(date);
            //若此目录不存在，则创建之// 这个东西只能简历一级文件夹，两级是无法建立的。。。。。
            File myPath = new File(toFilePath);
            if ( !myPath.exists()){
                myPath.mkdir();
            }
            File dest = new File(toFilePath, file.getOriginalFilename());
            file.transferTo(dest);
            //返回路径
            return "http://jtjs.aimanrenjian.net/family-app/static/chatimg/" + dateFormat.format(date) + "/" + file.getOriginalFilename();
        }

        catch (IOException e) {
            log.error("上传文件失败", e);
            return null;
        }
    }
}
